package com.youlu.campus.admin.card.service;

import com.youlu.campus.admin.card.dto.CardCategoryAllDTO;
import com.youlu.campus.admin.card.dto.CardCategoryDeleteDTO;
import com.youlu.campus.admin.card.dto.CardCategorySaveDTO;
import com.youlu.campus.admin.card.dto.CardCategorySearchDTO;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.entity.card.entity.CardCategory;
import com.youlu.campus.entity.card.entity.CardGoods;
import com.youlu.campus.service.platform.PlatformConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author : [dengbo]
 * @className : CardCategoryService
 * @description : [分类服务类]
 * @createTime : [2022/12/16 21:45]
 */
@Service
@Slf4j
public class CardCategoryService {

    @Value("${spring.profiles.active}")
    private String active;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private PlatformConfigService platformConfigService;

    public Page<CardCategory> list(CardCategorySearchDTO dto) {
        Query query = new Query();
        if (StringUtils.isNotBlank(dto.getCateName())) {
            query.addCriteria(Criteria.where("cateName").is(dto.getCateName()));
        }
        long count = mongoTemplate.count(query, CardCategory.class);
        query.with(Sort.by(Sort.Order.desc("createdTime")));
        PageRequest pageRequest = PageRequest.of(dto.getPage() - 1, dto.getPageSize());
        List<CardCategory> datas = mongoTemplate.find(query.with(pageRequest), CardCategory.class);
        Set<String> pids = new LinkedHashSet<>();
        for (CardCategory data : datas) {
            if (data.getParentId().equals("0")) {
                data.setPath(data.getCateName());
                data.setWebUrl(getPathUrl(data.getId()));
                data.setLevelId("1");
            } else {
                pids.add(data.getParentId());
                data.setLevelId("2");
                data.setCateImage(null);
            }
        }
        List<CardCategory> parent = mongoTemplate.find(new Query(Criteria.where("id").in(pids)), CardCategory.class);
        Map<String, CardCategory> map = parent.stream().collect(Collectors.toMap(CardCategory::getId, Function.identity(), (o1, o2) -> o2));
        datas.forEach(item -> {
            if (!item.getParentId().equals("0")) {
                CardCategory p = map.get(item.getParentId());
                if (p != null) {
                    item.setPath(p.getCateName() + ">" + item.getCateName());
                }
            }
        });
        return PageableExecutionUtils.getPage(datas, pageRequest, () -> count);
    }

    public String getPathUrl(String cateId){
        String cate = platformConfigService.getCardCatalogue();
        StringBuilder sb = new StringBuilder();
        sb.append(platformConfigService.getBizFrontPayDomain());
        sb.append(cate);
        sb.append("/index.html?a=1#/pages/buy-vip?cateId=");
        sb.append(cateId);
        if("prod".equals(active)){
            sb.append("&appId=wxe6d8878c1fad5938");
        }else{
            sb.append("&appId=wxbaba4b2c54e8881a");
        }
        return sb.toString();
    }

    public List<CardCategoryAllDTO> all() {
        Query query = new Query();
        query.addCriteria(Criteria.where("deleted").is(false));
        List<CardCategory> list = mongoTemplate.find(query, CardCategory.class);
        return getAllCateList(list, "0");
    }

    public List<CardCategoryAllDTO> getAllCateList(List<CardCategory> list, String parentId) {
        List<CardCategoryAllDTO> result = new ArrayList<>();
        List<CardCategory> sortList = list.stream().filter(item -> item.getParentId().equals(parentId)).sorted(Comparator.comparing(CardCategory::getPriority).reversed()).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(sortList)) {
            return result;
        }
        for (CardCategory category : sortList) {
            CardCategoryAllDTO dto = new CardCategoryAllDTO();
            dto.setCateName(category.getCateName());
            dto.setId(category.getId());
            dto.setChildren(getAllCateList(list, dto.getId()));
            result.add(dto);
        }
        return result;
    }

    public boolean save(CardCategorySaveDTO dto) {
        CardCategory category = null;
        if (StringUtils.isNotBlank(dto.getId())) {
            //修改
            category = mongoTemplate.findOne(Query.query(Criteria.where("id").is(dto.getId())), CardCategory.class);
            if (category == null) {
                throw new BusinessException("分类信息不存在");
            }
        }
        Date date = new Date();
        if (category == null) {
            category = new CardCategory();
            category.setCreatedTime(date);
            category.setDeleted(false);
        }
        category.setCateName(dto.getCateName());
        category.setCateImage(dto.getCateImage());
        category.setAccountTips(dto.getAccountTips());
        category.setPopupQrcode(dto.getPopupQrcode());
        category.setDescription(dto.getDescription());
        category.setPriority(dto.getPriority());
        if(StringUtils.isBlank(dto.getParentId()) || "0".equals(dto.getParentId())){
            category.setParentId("0");
            category.setLevelId("1");
        }else{
            category.setParentId(dto.getParentId());
            category.setLevelId("2");
        }
        category.setUpdatedTime(date);
        mongoTemplate.save(category);
        return true;
    }

    /**
     * 删除记录
     *
     * @param saveDTO
     * @return
     */
    public boolean delete(CardCategoryDeleteDTO saveDTO) {
        CardCategory category = mongoTemplate.findById(saveDTO.getId(), CardCategory.class);
        if (category == null) {
            throw new BusinessException("分类信息不存在");
        }
        if (category.getDeleted()) {
            category.setDeleted(false);
        } else {
            category.setDeleted(true);
        }
        mongoTemplate.save(category);
        return true;
    }

}
